package com.example.controller;

import com.example.bean.Result;
import com.example.config.OSSAliyunFileStorageService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;

/**
 *
 * @author weijingchen
 * @DateTime 2025-09-26
 */
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    @Autowired
    private OSSAliyunFileStorageService fileStorageService;
    @PostMapping("/upload")
    public Result<String> upload(@RequestPart("file") MultipartFile  file) throws IOException {

        // 校验是否为图片文件
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        } catch (Exception e) {
            throw new RuntimeException("上传图片失败");
        }

        if (file.getSize() == 0) {
            throw new RuntimeException("上传图片不能为空");
        }

        // 获得原始文件名
        String originalFilename = file.getOriginalFilename();
        // 获得文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;

        String filePath = fileStorageService.store(fileName, file.getInputStream());

        return Result.success(filePath);
    }
}
